//
//  VoiceReadItemDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2021/5/17.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "VoiceReadItemDetailViewController.h"
#import "RPAppShareView.h"
#import "VoiceReadItemFooterView.h"
#import "VoiceReadItemListView.h"
#import "VoiceReadDetailItemModel.h"
#import "VoiceReadDetailPlayerModel.h"
#import "VoiceReadPlayerItemModel.h"
#import "DFPlayer.h"

#import <MediaPlayer/MediaPlayer.h>

@interface VoiceReadItemDetailViewController ()<VoiceReadItemListViewDelegate,VoiceReadItemFooterViewDelegate,DFPlayerDelegate,DFPlayerDataSource>
@property (nonatomic,strong)VoiceReadItemFooterView *footerView;
@property (nonatomic,strong)VoiceReadItemListView *listView;
@property (nonatomic,strong)NSNumber *sortType;

@property (nonatomic,strong)DFPlayer *player;

/// 用来保存拖拽前的播放状态
@property (nonatomic,assign)DFPlayerState isDragBeforeState;

/// 最后一次的播放状态
@property (nonatomic,assign)DFPlayerState lastState;

/// 远程推送过来的状态
@property (nonatomic,assign)DFPlayerState remoteState;


@property (nonatomic,assign)DFPlayerState activityState;


@property (nonatomic,assign)DFPlayerState inHeadState;

@property (nonatomic,assign)CGFloat currentEndTime;

@property (nonatomic,strong)VoiceReadDetailItemModel *dtlModel;

@property (nonatomic,strong)NSMutableArray *urls;

@property (nonatomic,assign)BOOL isDraging;

@property (nonatomic,assign)BOOL isRemote;

@property (nonatomic,assign)BOOL isShowList;

@property (nonatomic,assign)BOOL isActivity;


@property (nonatomic,strong)UIImageView *backImgView;
@property (nonatomic,strong)UIButton *backBtn;

@property (nonatomic,strong)UIImageView *shareImgView;
@property (nonatomic,strong)UIButton *shareBtn;
@property (nonatomic,strong)UIView *navView;

@property (nonatomic,assign)NSInteger errorCount;

@property (nonatomic,strong)NSURLSessionTask *task;



@end

@implementation VoiceReadItemDetailViewController

- (NSMutableArray *)urls{
    if (!_urls) {
        _urls = [NSMutableArray array];
    }
    return _urls;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isRemote) {
        if (self.remoteState == DFPlayerStatePlaying) {
            [self.player df_play];
        }
        if (self.remoteState == DFPlayerStatePause) {
            [self.player df_pause];
        }
    }
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    NSArray *viewControllers = self.navigationController.viewControllers;
    // 判断是否推送点击离开页面
    if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) {
        
        if (self.player.state != DFPlayerStateStopped) {
            // 推送状态
            self.remoteState = self.player.state;
            // 暂停
            [self.player df_pause];
            // 远程事件
            self.isRemote = YES;
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.isActivity = YES;
   
    self.isHideNavBar = YES;
    
    
    // 父类的进度条隐藏
    self.myProgressView.hidden = YES;
    // 父类方法
    self.isUseSpin = YES;
    
    
    [self setupView];
    
    [self loadDataSource];
    
    [self setupPlayer];
    
    [self setupSourceArray];
    
}

- (void)setupView{
    
    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = [UIColor whiteColor];
    self.navView.alpha = 0;
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kNavBarHeight);
    }];
    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice_back_tag"]];
    [self.view addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.top.equalTo(self.view).offset(12 + GK_STATUSBAR_HEIGHT);
    }];
    self.shareImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice_share_tag"]];
    [self.view addSubview:self.shareImgView];
    [self.shareImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.centerY.equalTo(self.backImgView);
    }];
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(100, 60));
    }];
    self.shareBtn = [[UIButton alloc]init];
    [self.shareBtn addTarget:self action:@selector(shareMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareBtn];
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(100, 60));
    }];
    self.footerView = [[VoiceReadItemFooterView alloc]init];
    self.footerView.delegate = self;
    [self.view addSubview:self.footerView];
    
    self.footerView.cl_bottom = kScreenH;
    self.footerView.hidden = YES;
}

- (void)setupSourceArray{
    if (self.sourceArray.count == 0) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = @1;
        param[@"md5"] = [RPAppManager md5StrWithApi:VoicePlayList];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(VoicePlayList) parames:param success:^(id responseObj) {
            self.sourceArray = [VoiceReadPlayerItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
            [self dealVoiceListData];
            [self loadDataSource];
        } failure:^(id error) {
   
        }];
    }else{
        [self dealVoiceListData];
    }
}
- (void)dealVoiceListData{
    self.sortType = [[NSUserDefaults standardUserDefaults] objectForKey:@"sortType"];
    [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.index = @(idx + 1);
    }];
    if (self.sortType.intValue == 1) {
        self.sourceArray = [self.sourceArray sortedArrayUsingComparator:^NSComparisonResult(VoiceReadPlayerItemModel *_Nonnull obj1, VoiceReadPlayerItemModel *_Nonnull obj2) {
            return NSOrderedDescending;
        }];
    }
    [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DFPlayerModel *model = [[DFPlayerModel alloc]init];
        model.audioUrl = [NSURL URLWithString:obj.url];
        model.audioId = idx;
        [self.urls addObject:model];
    }];
    [self.player df_reloadData];
}

- (void)loadDataSource{
    [self.task cancel];
    if (self.sourceArray.count == 0) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.voiceId;
    param[@"md5"] = [RPAppManager md5StrWithApi:VoiceDetails];
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(VoiceDetails) parames:param success:^(id responseObj) {
        
        self.footerView.hidden = NO;
        
        self.dtlModel = [VoiceReadDetailItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
       
        NSArray *sourceArray = self.dtlModel.tvoiceResources;
        
        if (sourceArray.count > 1) {
            NSArray *result = [sourceArray sortedArrayUsingComparator:^NSComparisonResult(VoiceReadDetailPlayerModel *_Nonnull obj1, VoiceReadDetailPlayerModel * _Nonnull obj2) {
                NSInteger seq1 = obj1.seq.intValue;
                NSInteger seq2 = obj2.seq.intValue;
                if (seq1 > seq2) {
                    return NSOrderedDescending;
                }else if(seq1 < seq2){
                    return NSOrderedAscending;
                }
                return NSOrderedSame;
            }];
           self.dtlModel.tvoiceResources = result;
        }
                
        // 判断上层页面再播放
        if (self.currentModel != nil) {
            __block NSInteger index = -1;
            [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([self.currentModel.resourceId isEqualToNumber:obj.resourceId]) {
                    index = idx;
                }
            }];
            // 判断详情音源文件
            if (index == -1 && self.currentModel.status != XHPlayerListItemFailed) {
                self.currentModel.status = XHPlayerListItemFailed;
            }
        }else{
            VoiceReadDetailPlayerModel *videoModel = nil;
            if (sourceArray.count > 0) {
                videoModel = self.dtlModel.tvoiceResources.firstObject;
            }
            __block NSInteger index = -1;
            [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                // 判断currentModel 到时哪一个
                if (videoModel != nil && [videoModel.id isEqualToNumber:obj.resourceId]) {
                    index = idx;
                }
            }];
            if (index != -1) {
                self.currentModel = self.sourceArray[index];
            }else{
                self.currentModel = [self.sourceArray firstObject];
            }
            self.currentModel.currentTime = 0;
            self.currentModel.status = XHPlayerListItemReady;
          
            if (index == -1) {
                [self.player df_playWithAudioId:0];
            }else{
                [self.player df_playWithAudioId:index];
            }
        }
        
        [self.footerView setItemModel:self.currentModel];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)backMethod{
    
    if (self.isCenterMessage) {
        [self.player df_clearUserCache:NO];
        [self.player df_deallocPlayer];
        self.player = nil;
    }
    
    __weak typeof(self)weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        // 判断从列表页面进入
        if (weakSelf.playVoice && weakSelf.currentModel.status != XHPlayerListItemFailed) {
            weakSelf.playVoice(weakSelf.currentModel, weakSelf.beginTime,weakSelf.urls,weakSelf.sourceArray);
        // 从其他页面返回上层
        }else{
            // 判断是否在播放
            if (weakSelf.player.state == DFPlayerStatePlaying) {
                int totalTime = (int)(weakSelf.currentModel.totalTime * 1000);
                int currentTime = (int)(weakSelf.currentModel.currentTime * 1000);
                NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
                long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
                long long bTime = weakSelf.beginTime;
                long long count = dTime - bTime;
                [weakSelf saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
            }
            [weakSelf.player df_clearUserCache:NO];
            [weakSelf.player df_deallocPlayer];
            
            if (weakSelf.playOther) {
                weakSelf.playOther();
            }
        }
    }];
}
- (void)shareMethod{
    
    if (self.dtlModel == nil) {
        return;
    }
    
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;
            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;
            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.dtlModel.title descr:@"" thumImage:self.dtlModel.coverLog];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@media/audio?id=%@",HtmlUrl,self.dtlModel.id];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }];
}


- (void)saveVideoTime:(int)totalTime playTime:(long long)playTime beginTime:(long long)bTime endTime:(long long)endTime currentEndTime:(int)currentEndTime{
    
    if (bTime == 0) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"mediaTime"] = @(totalTime);
    param[@"playTime"] = @(playTime);
    param[@"startTime"] = @(bTime);
    param[@"endTime"] = @(endTime);
    param[@"mediaId"] = self.currentModel.id;
    param[@"resourceId"] = self.currentModel.resourceId;
    param[@"currentEndTime"] = @(currentEndTime);
    param[@"md5"] = [RPAppManager md5StrWithApi:SaveVoiceLog];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveVoiceLog) parames:param success:^(id responseObj) {

    } failure:^(id error) {

    }];
    
    self.beginTime = 0;
}

- (void)setupPlayer{
    if (self.isCenterMessage) {
        // 创建另一内存临时存储使用
        self.player = [[DFPlayer alloc]init];
        [self.player df_initPlayerWithUserId:nil];
        self.player.playMode = DFPlayerModeOrderCycle;
        self.player.isObserveWWAN = YES;
        self.player.isNeedCache = NO;
        self.player.delegate = self;
        self.player.dataSource = self;
    }else{
        self.player = [DFPlayer sharedPlayer];
        self.player.playMode = DFPlayerModeOrderCycle;
        self.player.delegate = self;
        self.player.dataSource = self;
    }
}

#pragma mark - DFPlayer
- (NSArray<DFPlayerModel *> *)df_audioDataForPlayer:(DFPlayer *)player{
    return self.urls;
}
- (void)df_player:(DFPlayer *)player progress:(CGFloat)progress currentTime:(CGFloat)currentTime{
    if (player.state == DFPlayerStatePause) {
        if (self.lastState != DFPlayerStatePause) {
            // 判断拖拽
            if (!self.isDraging) {
                // 普通暂停
                self.currentEndTime = [player currentTime];
            }
            int totalTime = (int)(player.totalTime * 1000);
            int currentTime = (int)(self.currentEndTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
        }
    }else if (player.state == DFPlayerStatePlaying){
        if (player.totalTime != 0 && self.beginTime == 0) {
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            self.beginTime = [[NSNumber numberWithDouble:time] longLongValue];
        }
        self.isDraging = NO;
    }else{
        self.isDraging = NO;
    }
    self.lastState = player.state;
    
    
    // 这里开始判断
    if (player.state == DFPlayerStatePlaying) {
        // 两层判断
        if (player.currentTime == 0) {
            self.currentModel.status = XHPlayerListItemReady;
        }else{
            // 判断是准备状态
            if (self.currentModel.status == XHPlayerListItemReady) {
                // 更新列表状态
                self.currentModel.status = XHPlayerListItemPlay;
                if (self.listView != nil) {
                    [self.listView updateListViewStatus];
                }
               
            }else{
                self.currentModel.status = XHPlayerListItemPlay;
            }
        }
    }else if (player.state == DFPlayerStatePause) {
        self.currentModel.status =XHPlayerListItemPause;
    }else{
        self.currentModel.status = XHPlayerListItemNormal;
    }
    
    self.currentModel.totalTime = player.totalTime;
    self.currentModel.currentTime = player.currentTime;
    

    [self.footerView setItemModel:self.currentModel];
    
    self.errorCount = 0;
    
}
- (void)df_playerDidPlayToEndTime:(DFPlayer *)player{
    [player df_next];
}
- (void)df_playerUpdateSeekTimeToPlay:(DFPlayer *)player{
    
    if (player.state == DFPlayerStatePlaying) {
        self.currentEndTime = [player currentTime];
        int totalTime = (int)(player.totalTime * 1000);
        int currentTime = (int)(self.currentEndTime * 1000);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
        long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
        long long bTime = self.beginTime;
        long long count = dTime - bTime;
        [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
    }
}

- (void)df_player:(DFPlayer *)player isInterrupted:(BOOL)isInterrupted{
    
    if (isInterrupted) {
        self.activityState = player.state;
        if (self.player.state == DFPlayerStatePlaying) {
            // 不执行更新状态栏函数 直接执行保存时间方法
            [self.player df_pause];
            int totalTime = (int)(self.currentModel.totalTime * 1000);
            int currentTime = (int)(self.currentModel.currentTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
            self.beginTime = 0;
        }
    }else{
        if (self.player.state == DFPlayerStatePause) {
            [self.player df_play];
        }
    }
}

- (void)df_playerEndedSeekTimeToPlay:(DFPlayer *)player{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
    self.beginTime = [[NSNumber numberWithDouble:time] longLongValue];
}

- (DFPlayerInfoModel *)df_audioInfoForPlayer:(DFPlayer *)player{
    NSInteger index = player.currentAudioModel.audioId;
    VoiceReadPlayerItemModel *voiceItemModel = self.sourceArray[index];
    if (self.currentModel != nil && self.currentModel.status == XHPlayerListItemPlay) {
        self.currentModel.status = XHPlayerListItemNormal;
        int totalTime = (int)(self.currentModel.totalTime * 1000);
        int currentTime = (int)(self.currentModel.currentTime * 1000);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
        long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
        long long bTime = self.beginTime;
        long long count = dTime - bTime;
        [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
    }
    
    BOOL isSame = [self.currentModel.resourceId isEqualToNumber:voiceItemModel.resourceId];
    
    self.beginTime = 0;
    
    voiceItemModel.currentTime = 0;
    
    self.currentModel = voiceItemModel;
    self.currentModel.status = XHPlayerListItemReady;
   
    DFPlayerInfoModel *infoModel = [[DFPlayerInfoModel alloc]init];
    infoModel.audioName = voiceItemModel.title;
    infoModel.audioSinger = voiceItemModel.author;
    NSString* strUrl = voiceItemModel.cover;
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:strUrl]];
    SDImageCache* cache = [SDImageCache sharedImageCache];
    //此方法会先从memory中取。
    UIImage *image = [cache imageFromDiskCacheForKey:key];
    infoModel.audioImage = image;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.voiceId = self.currentModel.id;
        if (!isSame) {
            // 请求详情接口
            [self loadDataSource];
        }
        [self.footerView setItemModel:self.currentModel];
    });
    
    [self loadUrl:[NSString stringWithFormat:@"%@media/audio?id=%@&isApp=true",HtmlUrl,voiceItemModel.id]];
    
    // 切换详情对象
    return infoModel;
}

// 进入后台
- (void)df_playerEnterBackGroundToPlay:(DFPlayer *)player{
    self.isActivity = NO;
}
// 进入前台
- (void)df_playerActivityToPlay:(DFPlayer *)player{
    self.isActivity = YES;
    
    if (self.activityState == DFPlayerStatePlaying) {
        [self.player df_play];
    }
    if (self.activityState == DFPlayerStatePause) {
        [self.player df_pause];
    }
}

//状态信息代理
- (void)df_player:(DFPlayer *)player didGetStatusCode:(DFPlayerStatusCode)statusCode{
    if (statusCode == DFPlayerStatusFailed || statusCode == DFPlayerStatusNoNetwork) {
        self.currentModel.status = XHPlayerListItemFailed;
        if (self.listView != nil) {
            NSInteger index = [self.sourceArray indexOfObject:self.currentModel];
            [self.listView reloadDataWithIndex:index];
        }
        // 判断是否展示列表
        if (!self.isShowList && self.isActivity) {
            [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
            [self.footerView setItemModel:self.currentModel];
            return;
        }
        self.errorCount++;
        if (self.sourceArray.count > 1 && self.errorCount > 1) {

            if ([self isErrorList]) return;
            // 判断是上一首播放出错还是下一首播放出错
            if (self.player.isLast) {
                [self.player df_last];
            }else{
                [self.player df_next];
            }
        }else{
            [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
            // 判断是否全部播放失败
            if ([self isErrorList]) return;
            // 播放下一个
            if (self.player.isLast) {
                [self.player df_last];
            }else{
                [self.player df_next];
            }
        }
    }
}
- (void)df_playerFailToPlay:(DFPlayer *)player StatusCode:(NSInteger)statusCode{
    
    self.currentModel.status = XHPlayerListItemFailed;
    if (self.listView != nil) {
        NSInteger index = [self.sourceArray indexOfObject:self.currentModel];
        [self.listView reloadDataWithIndex:index];
    }
    // 判断是否展示列表
    if (!self.isShowList && self.isActivity) {
        [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
        return;
    }
    self.errorCount++;
    if (self.sourceArray.count > 1 && self.errorCount > 1) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self isErrorList]) return;
            // 判断是否是最后一个
            if (self.player.isLast) {
                [self.player df_last];
            }else{
                [self.player df_next];
            }
            [self.footerView setItemModel:self.currentModel];
        });
    }else{
        [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 判断是否是最后一个
            if ([self isErrorList]) return;
            if (self.player.isLast) {
                [self.player df_last];
            }else{
                [self.player df_next];
            }
            [self.footerView setItemModel:self.currentModel];
        });
    }
}
- (void)df_player:(DFPlayer *)player isHeadphone:(BOOL)isHeadphone{
    
    if (!isHeadphone) {
        
        if (self.currentModel.status == XHPlayerListItemPlay) {
            
            self.currentModel.status = XHPlayerListItemPause;
            
            [self.player df_pause];
            
            int totalTime = (int)(self.currentModel.totalTime * 1000);
            int currentTime = (int)(self.currentModel.currentTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];

            [self.footerView setItemModel:self.currentModel];

            NSInteger index = [self.sourceArray indexOfObject:self.currentModel];
            
            [self.listView reloadDataWithIndex:index];
            
            self.inHeadState = DFPlayerStatePlaying;
            
        }else if (self.currentModel.status == XHPlayerListItemPause){
            self.inHeadState = DFPlayerStatePause;
        }

    }else{
        if (self.inHeadState == DFPlayerStatePlaying) {
            [self.player df_play];
        }else if (self.inHeadState == DFPlayerStatePause){
            [self.player df_pause];
        }

    }
}

#pragma mark - VoiceReadItemFooterViewDelegate
- (void)showAllVoice{
    self.isShowList = YES;
    [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (self.currentModel != nil && [self.currentModel.resourceId isEqualToNumber:obj.resourceId]) {
            obj.status = self.currentModel.status;
        }else{
            obj.status = XHPlayerListItemNormal;
        }
    }];
    self.listView = [[VoiceReadItemListView alloc]initWithSourceArray:self.sourceArray delegate:self];
    [self.listView show];
}
- (void)nextPlay{
    [self.player df_next];
}
- (void)lastPlay{
    [self.player df_last];
}
- (void)continuePlay{
    [self.player df_play];
    
}
- (void)pausePlay{
    [self.player df_pause];
}
- (void)dismissListView{
    self.listView = nil;
    self.isShowList = NO;
}

- (void)sliderBegan{
    
    self.isDragBeforeState = [self.player state];
    
    self.isDraging = YES;
    self.currentEndTime = [self.player currentTime];
    [self.player df_pause];
}
- (void)sliderEnded:(CGFloat)value{
    self.isDraging = NO;
    __weak typeof(self)weakSelf = self;
    [self.player df_seekToTime:value completionBlock:^{
        if (weakSelf.isDragBeforeState == DFPlayerStatePause) {
            [self.player df_pause];
        }
    }];
}

- (void)startPlay{

    NSInteger index = [self.sourceArray indexOfObject:self.currentModel];
    [self.player df_playWithAudioId:index];
    
}

- (BOOL)isErrorList{
    __block BOOL isError = YES;
    [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.status != XHPlayerListItemFailed) {
            isError = NO;
            *stop = YES;
        }
    }];
    return isError;
}

#pragma mark - VoiceReadItemListViewDelegate
- (void)updateSortType:(NSNumber *)sortType sourceArray:(nonnull NSArray *)sourceArray{
    self.sortType = sortType;
    self.sourceArray = sourceArray;
    
    [self.urls removeAllObjects];
    
    [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DFPlayerModel *model = [[DFPlayerModel alloc]init];
        model.audioUrl = [NSURL URLWithString:obj.url];
        model.audioId = idx;
        [self.urls addObject:model];
    }];
    
    [self.player df_reloadData];
    
    [[NSUserDefaults standardUserDefaults] setObject:sortType forKey:@"sortType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)playCurrentVoiceByIndex:(NSInteger)index{
    
    self.errorCount = 0;
    
    self.currentModel.status = XHPlayerListItemNormal;
    
    // 记录保存当前时间
    int totalTime = (int)(self.currentModel.totalTime * 1000);
    int currentTime = (int)(self.currentModel.currentTime * 1000);
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
    long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
    long long bTime = self.beginTime;
    long long count = dTime - bTime;
    [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
    
    
    NSInteger lastIndex = [self.sourceArray indexOfObject:self.currentModel];
    
    if (self.listView != nil) {
        [self.listView reloadDataWithIndex:lastIndex];
    }

    [self.player df_playWithAudioId:index];
}
- (void)continueCurrentVoiceByIndex:(NSInteger)index{
    
    VoiceReadPlayerItemModel *currentModel = self.sourceArray[index];
    
    currentModel.status = XHPlayerListItemPlay;
    
    [self.player df_play];
    
    if (self.listView != nil) {
        [self.listView reloadDataWithIndex:index];
    }
}
- (void)pauseCurrentVoiceByIndex:(NSInteger)index{
    
    VoiceReadPlayerItemModel *currentModel = self.sourceArray[index];
    
    currentModel.status = XHPlayerListItemPause;
    
    [self.player df_pause];
    
    if (self.listView != nil) {
        [self.listView reloadDataWithIndex:index];
    }
}
- (NSNumber *)getNewSortType{
    return self.sortType;
}

- (void)showBottomView{
    self.footerView.hidden = NO;
}
- (void)hideBottomView{
    self.footerView.hidden = YES;
}

@end
